import * as fs from 'fs';
import * as path from 'path';
import semver from 'semver';
import * as os from 'os';
import { BrowserConfig, SaveBrowserConfig } from '../types/browser';

export function generateUserAgent(): string {
  const chromeVersions = ['114.0.0.0', '115.0.0.0', '116.0.0.0', '117.0.0.0', '118.0.0.0', '119.0.0.0'];
  const platforms = {
    win: {
      os: 'Windows NT 10.0; Win64; x64',
      platform: 'Windows'
    },
    mac: {
      os: 'Macintosh; Intel Mac OS X 10_15_7',
      platform: 'macOS'
    },
    linux: {
      os: 'X11; Linux x86_64',
      platform: 'Linux'
    }
  } as const;

  const randomChrome = chromeVersions[Math.floor(Math.random() * chromeVersions.length)];
  const platformKeys = ['win', 'mac', 'linux'] as const;
  const randomPlatform = platforms[platformKeys[Math.floor(Math.random() * platformKeys.length)] as keyof typeof platforms];

  return `Mozilla/5.0 (${randomPlatform.os}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${randomChrome} Safari/537.36`;
}

export async function withTimeout<T>(promise: Promise<T>, timeoutMs: number = 2000): Promise<T> {
  return Promise.race([
    promise,
    new Promise<T>((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs))
  ]);
}

export function getChromePath(customPath?: string): string {
  // 如果提供了自定义路径且路径存在，优先使用自定义路径
  if (customPath) {
    try {
      const stats = fs.statSync(customPath);
      if (stats.isFile()) {
        if (process.platform !== 'win32') {
          const mode = stats.mode;
          if ((mode & 0o111) !== 0) {
            console.debug(`Using custom Chrome path: ${customPath}`);
            return customPath;
          }
        } else {
          console.debug(`Using custom Chrome path: ${customPath}`);
          return customPath;
        }
      }
    } catch (error) {
      console.debug(`Custom Chrome path not valid: ${customPath}`);
    }
  }

  // 默认路径查找
  const platform = process.platform;
  let paths: string[] = [];

  switch (platform) {
    case 'win32':
      paths = [
        'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
        'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
        process.env.LOCALAPPDATA + '\\Google\\Chrome\\Application\\chrome.exe'
      ];
      break;
    case 'darwin':
      paths = [
        '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
        path.join(process.env.HOME || '', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome')
      ];
      break;
    case 'linux':
      paths = [
        '/usr/bin/google-chrome',
        '/usr/bin/google-chrome-stable'
      ];
      break;
  }

  // 验证每个路径
  for (const chromePath of paths) {
    try {
      const stats = fs.statSync(chromePath);
      if (stats.isFile()) {
        if (platform !== 'win32') {
          const mode = stats.mode;
          if ((mode & 0o111) !== 0) {
            console.debug(`Found executable Chrome at: ${chromePath}`);
            return chromePath;
          }
        } else {
          console.debug(`Found Chrome at: ${chromePath}`);
          return chromePath;
        }
      }
    } catch (error) {
      console.debug(`Chrome not found at: ${chromePath}`);
      continue;
    }
  }

  throw new Error('找不到Chrome浏览器，请确保已安装Google Chrome或提供正确的安装路径');
}

export function cleanUserDataDirectory(userDataDir: string) {
  try {
    const filesToClean = [
      'SingletonLock',
      'SingletonSocket',
      'Singleton'
    ];

    for (const file of filesToClean) {
      const filePath = path.join(userDataDir, file);
      if (fs.existsSync(filePath)) {
        fs.unlinkSync(filePath);
      }
    }
  } catch (error) {
    console.error('Failed to clean user data directory:', error);
  }
}

export function validateBrowserConfig(config: SaveBrowserConfig): boolean {
  if (!config) return false;
  if (typeof config.id !== 'string' || !config.id.trim()) return false;
  if (typeof config.name !== 'string' || !config.name.trim()) return false;
  
  // 检查ID格式
  if (!/^\d+$/.test(config.id)) return false;
  
  // 检查名称长度
  if (config.name.length > 50) return false;
  
  return true;
}

export function getDefaultChromeUserDataDir(): string {
  const platform = process.platform;
  let defaultUserDataDir = '';

  switch (platform) {
    case 'win32':
      defaultUserDataDir = path.join(process.env.LOCALAPPDATA || '', 'Google/Chrome/User Data');
      break;
    case 'darwin':
      defaultUserDataDir = path.join(os.homedir(), 'Library/Application Support/Google/Chrome');
      break;
    case 'linux':
      defaultUserDataDir = path.join(os.homedir(), '.config/google-chrome');
      break;
  }

  // 验证目录是否存在
  try {
    const stats = fs.statSync(defaultUserDataDir);
    if (stats.isDirectory()) {
      return defaultUserDataDir;
    }
  } catch (error) {
    console.debug(`Default Chrome user data directory not found at: ${defaultUserDataDir}`);
  }

  throw new Error('找不到Chrome浏览器默认用户数据目录，请确保已安装Google Chrome');
}

export function getDefaultChromeExtensionsDir(): string {
  const platform = process.platform;
  let extensionsDir = '';

  switch (platform) {
    case 'win32':
      extensionsDir = path.join(process.env.LOCALAPPDATA || '', 'Google/Chrome/User Data/Default/Extensions');
      break;
    case 'darwin':
      extensionsDir = path.join(os.homedir(), 'Library/Application Support/Google/Chrome/Default/Extensions');
      break;
    case 'linux':
      extensionsDir = path.join(os.homedir(), '.config/google-chrome/Default/Extensions');
      break;
  }

  // 验证目录是否存在
  try {
    const stats = fs.statSync(extensionsDir);
    if (stats.isDirectory()) {
      return extensionsDir;
    }
  } catch (error) {
    console.debug(`Default Chrome extensions directory not found at: ${extensionsDir}`);
  }

  throw new Error('找不到Chrome浏览器默认插件目录，请确保已安装Google Chrome');
} 

// 获取所有扩展的完整路径（带最新版本）
export function getChromeExtensions(): string[] {
  const extensionsDir = getDefaultChromeExtensionsDir();
  if (!fs.existsSync(extensionsDir)) return [];

  return fs.readdirSync(extensionsDir).flatMap(extId => {
    const extDir = path.join(extensionsDir, extId);
    try {
      const versions = fs.readdirSync(extDir)
        .sort((a, b) => semver.rcompare(a, b, true)); // 按版本降序

      return versions.map(version =>
        `"${path.join(extDir, version)}"` // 引号处理路径空格
      ).slice(0, 1); // 只取最新版本
    } catch (error) {
      console.debug(`跳过无效扩展 ${extId}:`, error);
      return [];
    }
  });
}

// 获取扩展参数, TODO
export const getExtensionArgs = () => {

  // 从一个静态文目录获取插件 
  // const extensions = fs.readdirSync(extensionsDir);

  // // 修复加载扩展的多个问题：
  // // 1. 使用自动获取的扩展路径而不是硬编码路径
  // // 2. 移除路径中的多余引号（Puppeteer会自动处理路径空格）
  // // 3. 确保扩展目录存在且包含manifest.json
  // const extensionArgs = extensions.map(extPath => {
  //   const normalizedPath = extPath.replace(/"/g, ''); // 移除路径引号
  //   console.log('正在验证扩展路径:', normalizedPath);

  //   // 检查扩展目录是否存在
  //   if (!fs.existsSync(normalizedPath)) {
  //     console.error('扩展路径不存在:', normalizedPath);
  //     return '';
  //   }

  //   // 检查manifest文件是否存在
  //   const manifestPath = path.join(normalizedPath, 'manifest.json');
  //   if (!fs.existsSync(manifestPath)) {
  //     console.error('扩展缺少manifest文件:', normalizedPath);
  //     return '';
  //   }

  //   return `--load-extension=${normalizedPath}`;
  // }).filter(arg => arg); // 过滤无效路径

  // return extensionArgs;

  return [];
}